<script lang="ts" setup>
import { computed, reactive, ref } from "vue";
import api from "@/api";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { MachineGroupSaveCmd } from "@/types";

const emit = defineEmits(["success"]);

const state = reactive({
  visible: false,
  form: new MachineGroupSaveCmd()
});

const title = computed(() => {
  return state.form.id ? "编辑主机组" : "新建主机组";
});

const formRef = ref<FormInstance | null>(null);

const rules: FormRules<MachineGroupSaveCmd> = {
  name: [{ required: true, message: "请输入", trigger: ["blur", "change"] }]
};

const submit = () => {
  formRef.value?.validate((valid, fields) => {
    if (valid) {
      api.machineGroup.saveMachineGroup(state.form).then(() => {
        ElMessage.success("保存成功");
        emit("success");
        state.visible = false;
      });
    }
  });
};

const reset = () => {
  state.form = new MachineGroupSaveCmd();
  formRef.value?.resetFields();
};

const openDialog = (id?: string) => {
  state.visible = true;
  if (id) {
    // state.form.id = id;
    api.machineGroup.getMachineGroup(id).then((data) => {
      state.form = data.data;
    });
  }
};

const closeDialog = () => {
  state.visible = false;
};

defineExpose({
  openDialog,
  closeDialog
});
</script>

<template>
  <el-dialog
    v-model="state.visible"
    :title="title"
    :close-on-click-modal="false"
    width="600"
    @open="reset"
  >
    <div>
      <el-form
        :model="state.form"
        label-width="auto"
        ref="formRef"
        :rules="rules"
        style="max-width: 600px"
      >
        <el-form-item label="主机组名称" prop="name">
          <el-input v-model="state.form.name" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="state.visible = false">取消</el-button>
        <el-button type="primary" @click="submit"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
